<!--
* description: 整车销售---订单配车
* author:xlc
* createdDate: 2020-11-17
-->
<template>
  <div class="app-container app-container-table">
    <el-dialog
      v-dialogDrag
      v-loading="dialogLoading"
      style="margin:15px"
      :visible="popupsVisible"
      :title="titleName"
      center
      width="90%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader slot="title" :title="titleName" :style-type="$store.state.app.dialogType" />
      <div>
        <!-- 表单组件 -->
        <!-- 批量手动配车 -->
        <one-table-template
          v-if="isshow==='batch'"
          ref="multipleTable"
          :dynamic-buttons="tableButtons"
          :dynamic-api-config="apiConfig"
          :dynamic-table-cols="tableCols"
          :dynamic-form-fields="formField"
          :dynamic-is-show-select="false"
          :dynamic-is-show-more-btn="true"
          :dynamic-page-size="-1"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
        />
        <!-- 导入配车 -->
        <one-table-template
          v-if="isshow==='import'"
          ref="multipleTable"
          :dynamic-buttons="tableButtonsImport"
          :dynamic-table-cols="tableColsImport"
          :dynamic-is-show-select="false"
          :dynamic-is-show-more-btn="true"
          :dynamic-page-size="-1"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
        />
        <!-- 配车 -->
        <one-table-template
          v-if="isshow==='car'"
          ref="multipleTable"
          :dynamic-components="tableComponentsCar"
          :dynamic-buttons="tableButtonsCar"
          :dynamic-api-config="apiConfig"
          :dynamic-table-cols="tableColsCar"
          :dynamic-form-fields="formField"
          :dynamic-is-show-select="true"
          :dynamic-is-show-more-btn="true"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
        />
      </div></el-dialog>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { orgApis } from '@/api/vesalesapi.js'
import { exportExcel } from '@/utils/getTimeString.js'
import OneTableTemplate from '@/components/templates/oneTable'
import dialogHeader from '@/components/dialogHeader'
import Vue from 'vue'
export default {
  components: {
    OneTableTemplate,
    dialogHeader
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'supplierMessage-edit'], () => {
      next()
    })
  },
  props: {
    popupsVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Array,
      default: () => []
    },
    isshow: {
      type: String,
      default: ''
    },
    titleName: {
      type: String,
      default: '配车'
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      dialogLoading: false,
      // 是否已导入
      isImport: false,
      // 网格查询API配置对象
      apiConfig: orgApis.orderMatchCarAllotQuery,
      selectrow: {},
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.batchMatchCar(),
          text: '批量手工配车', // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(1),
          text: '导出',
          name: 'export',
          position: 'right'
        }
      ],
      tableButtonsImport: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.importcar(),
          text: '导入配车',
          name: 'import', // 按钮图标样式
          position: 'upload'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          clickEvent: () => this.download(),
          text: '下载模板',
          name: 'download',
          position: 'right'
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'showDetial',
          position: 'right'
        }
      ],
      tableButtonsCar: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          name: 'search', // 按钮图标样式
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          name: 'reset',
          position: 'right'
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.save(),
          disabled: true,
          text: this.$t('sys.button.confirm'),
          name: 'confirm',
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          clickEvent: () => this.closeEdit(),
          text: this.$t('sys.button.cancel'),
          name: 'cancel',
          position: 'left'
        }
      ],
      // 动态组件-查询条件
      tableComponentsCar:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '销售计划号：',
              codeField: 'salePlanCode',
              isMul: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '仓库名称：',
              codeField: 'stockId',
              component: () => import('@/components/org/commonSelect'),
              customObj: { api: orgApis.ListOfCityWarehouse, selectType: '1', listQuery: { warehouseId: '1' }},
              oFields: 'stockId,stockName',
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '库存天数：',
              codeField: 'firstInDlrstockDate',
              isMul: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey18',
              labelName: '车系：',
              disabled: true,
              codeField: 'carSeriesCn',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey14',
              labelName: '基础车型：',
              codeField: 'carConfigCn',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey15',
              labelName: '选装包：',
              disabled: true,
              codeField: 'optionalPag',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey16',
              labelName: '车身颜色：',
              disabled: true,
              codeField: 'carColorName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey17',
              disabled: true,
              labelName: '内饰颜色：',
              codeField: 'carIncolorName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            }
          ],
      // 动态生成网格列
      tableCols:
        [
          {
            prop: 'saleOrderCode',
            label: '订单编号',
            width: 160
          },
          {
            prop: 'remark',
            label: '批量配车说明',
            width: 160
          },
          {
            prop: 'orderStatusName',
            label: '订单状态',
            width: 160
          },
          {
            prop: 'custName',
            label: '客户名称',
            width: 160
          },
          {
            prop: 'custLxPhone',
            label: '客户联系电话',
            width: 160
          },
          {
            prop: 'salePlanCode',
            label: '销售计划号',
            width: 160
          },
          {
            prop: 'vin',
            label: 'VIN码',
            width: 160
          },
          {
            prop: 'carSeriesCn',
            label: '车系',
            width: 160
          },
          {
            prop: 'carConfigCn',
            label: '基础车型名称',
            width: 160
          },
          {
            prop: 'optionalPag',
            label: '选装包',
            width: 160
          },
          {
            prop: 'carColorName',
            label: '车身颜色',
            width: 160
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色',
            width: 160
          },
          {
            prop: 'carHouseName',
            label: '仓库名称',
            width: 160
          }
        ],
      tableColsImport:
        [
          {
            prop: 'remark',
            label: '导入配车说明',
            width: 160
          },
          {
            prop: 'SaleOrderCodeC',
            label: 'C端订单号',
            width: 160
          },
          {
            prop: 'orderStatus',
            label: '订单状态',
            width: 160
          },
          {
            prop: 'custName',
            label: '客户名称',
            width: 160
          },
          {
            prop: 'custTEL',
            label: '客户联系电话',
            width: 160
          },
          {
            prop: 'vin',
            label: 'VIN码',
            width: 160
          },
          {
            prop: 'salePlanCode',
            label: '销售计划号',
            width: 160
          },
          {
            prop: 'carConfigCN',
            label: '基础车型名称',
            width: 160
          },
          {
            prop: 'optionalPagName',
            label: '选装包',
            width: 160
          },
          {
            prop: 'carColorName',
            label: '车身颜色',
            width: 160
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色',
            width: 160
          },
          {
            prop: 'carHouseName',
            label: '仓库名称',
            width: 160
          }
        ],
      tableColsCar: [
        {
          prop: 'salePlanCode',
          label: '销售计划号',
          width: 160
        },
        {
          prop: 'vin',
          label: 'VIN码',
          width: 160
        },
        {
          prop: 'carSeriesCn',
          label: '车系',
          width: 160
        },
        {
          prop: 'carConfigCN',
          label: '基础车型名称',
          width: 160
        },
        {
          prop: 'optionalPagName',
          label: '选装包',
          width: 160
        },
        {
          prop: 'carColorName',
          label: '车身颜色',
          width: 160
        },
        {
          prop: 'carIncolorName',
          label: '内饰颜色',
          width: 160
        },
        {
          prop: 'firstInDlrstockDate',
          label: '库存天数',
          width: 160
        },
        {
          prop: 'carHouseName',
          label: '仓库名称',
          width: 160
        },
        {
          prop: 'offlineDate',
          label: '车辆下线时间',
          width: 160
        }
      ],
      formField: {
        salePlanCode: '',
        vin: '',
        stockId: '',
        firstInDlrstockDate: ''
      },
      refreshTableKey: '',
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 手动勾选时
        onCheckSelect: (selection, row) => {
          // 清除所有选中
          this.selectrow = row
          this.$refs.multipleTable.$refs.multipleTable.clearSelection()
          if (selection.length === 0) return
          // 将当前点击项选中
          this.$refs.multipleTable.$refs.multipleTable.toggleRowSelection(row, true)
        },
        onCheckSelectChange: (selection) => {
          this.onCheckSelectChange1(selection)
        }
      }
    }
  },
  created() {
    if (this.isshow === 'car') {
      var obj = {
        saleOrderId: this.dataForForm[0].saleOrderId,
        INSERT_ORDER_STATUS: this.dataForForm[0].INSERT_ORDER_STATUS,
        updateControlId: this.dataForForm[0].updateControlId,
        carConfigId: this.dataForForm[0].carConfigId,
        carSeriesId: this.dataForForm[0].carSeriesId,
        carColorId: this.dataForForm[0].carColorId,
        carIncolorId: this.dataForForm[0].carIncolorId,
        optionalPagId: this.dataForForm[0].optionalPagId,
        carSeriesCn: this.dataForForm[0].carSeriesCn,
        carConfigCn: this.dataForForm[0].carConfigCn,
        optionalPag: this.dataForForm[0].optionalPag,
        carColorName: this.dataForForm[0].carColorName,
        carIncolorName: this.dataForForm[0].carIncolorName
      }
      Object.assign(this.formField, obj)
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.isshow === 'batch') {
        this.$refs.multipleTable.list = this.dataForForm
        this.$refs.multipleTable.pageTotal = this.dataForForm.length
      } else if (this.isshow === 'car') {
        this.queryTable(1)
      }
    })
  },
  methods: {
    // 批量手工配车
    batchMatchCar() {
      var data = this.$refs.multipleTable.list
      var isbanch = data.every(item => {
        return !item.remark
      })
      if (!isbanch) { this.$message('不可重复配车'); return }
      this.dialogLoading = true
      const that = this
      const queryObj = {
        // api配置
        apiConfig: orgApis.batchCarAllocation,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: data
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.dialogLoading = false
          this.$refs.multipleTable.list = response.rows
          this.$refs.multipleTable.pageTotal = response.rows.length
          this.$message({
            message: response.msg,
            duration: 2000
          })
        }
      })
    },
    // 设置确认按钮开关
    onCheckSelectChange1(selection) {
      var btn1 = this.tableButtonsCar[2]
      const isCheck = selection && selection.length > 0
      btn1.disabled = !isCheck
    },
    // 上传前
    handleChange(param) { this.attachHandleChange(param) },
    beforeAvatarUpload(file) {},
    handFileListChange(file, fileList) {},
    importcar() {},
    // 上传
    attachHandleChange(param) {
      const loading = this.$loading({
        text: '正在导入'
      })
      const that = this
      const url = orgApis.orderMatchCarImpport.APIUrl
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close()
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          if (response.result === '1') {
            this.isImport = true
            this.$refs['multipleTable'].handleResponseRestful(response, 1, -1)
          }
        })
        .catch((err) => {
          loading.close()
          that.modeCode = ''
          console.info(err)
        })
    },
    // 下载模板
    download() {
      exportExcel({ method: 'get' }, orgApis.orderMatchCarImpportModelDownload.APIUrl, orgApis.orderMatchCarImpportModelDownload.ServiceCode, '下载配车模板')
    },
    // 导出
    exportExcel111(val) {
      var apiconfig = val === 1 ? orgApis.importCarExport : orgApis.orderMatchCarImpportState
      var name = val === 1 ? '批量导入配车' : '导入配车'
      exportExcel({ exportData: this.$refs.multipleTable.list }, apiconfig.APIUrl, apiconfig.ServiceCode, name)
    },
    // 关闭弹窗
    closeEdit(type) {
      if (this.isshow === 'import' && this.isImport !== true) {
        type = ''
      } else {
        type = '1'
      }
      this.$emit('close', type)
    },
    // 保存saleOrderDate  custType firstInHoststockDate
    // carHouseCode 城市仓库编码
    // dlrCode 交付门店编码
    // saleDlrCode saleDlrCode 销售门店编码
    // saleOrderCodeC c端订单号
    // carConfigCode 车型编码
    // carColorCode 车身颜色编码
    // carIncolorCode 内饰颜色编码
    // optionalPagCode 选装包编码
    save() {
      var obj = {
        carHouseCode: this.dataForForm[0].carHouseCode,
        deliveryFacHwCode: this.dataForForm[0].deliveryFacHwCode,
        dlrCode: this.dataForForm[0].dlrCode,
        saleDlrCode: this.dataForForm[0].saleDlrCode,
        saleOrderDate: this.dataForForm[0].saleOrderDate,
        custType: this.dataForForm[0].custType,
        saleOrderId: this.dataForForm[0].saleOrderId,
        saleOrderCode: this.dataForForm[0].saleOrderCode,
        updateControlId: this.dataForForm[0].updateControlId,
        updateControlIdD: this.dataForForm[0].updateControlIdD,
        saleOrderCodeC: this.dataForForm[0].saleOrderCodeC,
        deliveryDlrId: this.dataForForm[0].deliveryDlrId,
        vin: this.selectrow.vin,
        firstInHoststockDate: this.selectrow.firstInHoststockDate,
        carHouseCodeS: this.selectrow.carHouseCodeS,
        DLR_ID: this.selectrow.DLR_ID,
        carId: this.selectrow.carId,
        stockId: this.selectrow.stockId,
        carSeriesCode: this.selectrow.carSeriesCode,
        carConfigCode: this.selectrow.carConfigCode,
        optionalPagCode: this.selectrow.optionalPagCode,
        carIncolorCode: this.selectrow.carIncolorCode,
        carColorCode: this.selectrow.carColorCode,
        InstoreTime: this.selectrow.InstoreTime,
        salePlanCode: this.selectrow.salePlanCode
      }
      this.$emit('save', obj)
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-table__header .el-checkbox{
  display:none
}
</style>
